import { defineStore } from 'pinia'
import { ref } from 'vue'
import { fetchWeatherByCity } from '../services/weatherApi'

export interface WeatherData {
  city: string
  province?: string
  temperature: number
  weather: string
  windDirection?: string
  windPower?: number
  humidity?: string
}

export const useWeatherStore = defineStore('weather', () => {
  const weatherData = ref<WeatherData | null>(null)
  const loading = ref(false)
  const error = ref<string | null>(null)

  const fetchWeather = async (cityName: string) => {
    loading.value = true
    error.value = null
    
    try {
      // 调用天气API（根据配置决定使用真实API还是模拟数据）
      const apiData = await fetchWeatherByCity(cityName)
      
      // 数据验证和默认值处理
      const validatedData: WeatherData = {
        city: apiData.city || cityName,
        province: apiData.province || undefined,
        temperature: Math.round(apiData.temperature || 0),
        weather: apiData.weather || '未知',
        windDirection: apiData.windDirection || undefined,
        windPower: apiData.windPower || undefined,
        humidity: typeof apiData.humidity === 'number' 
          ? `${apiData.humidity}%` 
          : apiData.humidity || undefined
      }
      
      weatherData.value = validatedData
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取天气信息失败'
      weatherData.value = null
    } finally {
      loading.value = false
    }
  }

  const clearWeather = () => {
    weatherData.value = null
    error.value = null
  }

  return {
    weatherData,
    loading,
    error,
    fetchWeather,
    clearWeather
  }
})
